import type { Response } from "@/interface/Response";

const PostHeader = { "content-type": "application/x-www-form-urlencoded" };
const GetHeader = { "content-type": "application/json" };

export const Request = (url: string, method: any, data?: any) => {
  let met = method ?? "GET";

  return new Promise<any>((resolve, reject) => {
    uni.request({
      url: url,
      data: data,
      method: met,
      success: (res) => {
        console.log(res);
        let Result: Response.ApiReqsult = res.data as Response.ApiReqsult;
        if (res.statusCode != 200 && res.statusCode) {
          let StatusCode = GetStatusCode(res.statusCode);
          resolve(<Response.ApiReqsult>{
            code: StatusCode?.status,
            msg: StatusCode?.msg,
          });
          return;
        }
        resolve(Result);
      },
      fail: (e) => {
        resolve(<Response.ApiReqsult>{
          code: -1,
          msg: e.errMsg,
        });
      },
      header: GetHeader,
    });
  });
};

function GetStatusCode(status: number) {
  let code = StatusCode.find((d) => d.status == status);
  return code;
}

const StatusCode = [
  {
    status: 400,
    msg: "错误的请求",
  },
  {
    status: 401,
    msg: "未经授权",
  },
  {
    status: 404,
    msg: "404 not found",
  },
  {
    status: 405,
    msg: "请求的方法被禁止，请检查请求方式是否与后台一致",
  },
  {
    status: 415,
    msg: "不支持的数据类型",
  },
  {
    status: 500,
    msg: "内部服务器错误",
  },
  {
    status: 508,
    msg: "检测到循环",
  },
];
